/**
 * 
 */
package fr.paulmasson.jfreex.ui;

import java.util.ArrayList;
import java.util.TreeSet;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import fr.paulmasson.jfreex.replay.ReplayChannel;

/**
 * @author Paul MASSON : contact@paulmasson.fr
 * @version 11.7.13
 */
public class ReplayList {

	public static Composite create(Composite father, final TreeSet<ReplayChannel> replayChannels) {

		final ScrolledComposite scrollComposite = new ScrolledComposite(father, SWT.V_SCROLL | SWT.BORDER);

		final Table table = new Table(scrollComposite, SWT.MULTI | SWT.FULL_SELECTION);
		table.setLinesVisible(true);
		table.setHeaderVisible(false);
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.heightHint = 200;
		table.setLayoutData(data);
		String[] titles = { " " };
		for (int i = 0; i < titles.length; i++) {
			TableColumn column = new TableColumn(table, SWT.NONE);
			column.setText(titles[i]);
		}

		for (ReplayChannel replayChannel : replayChannels) {
			TableItem item = new TableItem(table, SWT.NONE);
			item.setText(0, replayChannel.getTitle());
			try {
				item.setImage( 0, new Image(Display.getCurrent(), replayChannel.getIconPath()));
			} catch (Exception e) {
			}

		}

		for (int i = 0; i < titles.length; i++) {
			table.getColumn(i).pack();
		}

		scrollComposite.setContent(table);
		scrollComposite.setExpandVertical(true);
		scrollComposite.setExpandHorizontal(true);

		table.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
			}

			/**
			 * DefaultSelected equals Double-click
			 */
			@Override
			public void widgetDefaultSelected(SelectionEvent evt) {
				int index = table.getSelectionIndex() + 1;
				for (ReplayChannel c : replayChannels) {
					if (c.getId() == index) {
						fireChannelChanged(c);
						break;
					}
				}
			}
		});

		return scrollComposite;
	}

	private static ArrayList<ChannelsListListener> listeners = new ArrayList<ChannelsListListener>();

	public void addChannelsListListener(ChannelsListListener listener) {
		listeners.add(listener);
	}

	private static void fireChannelChanged(ReplayChannel channel) {
		for (ChannelsListListener listener : listeners) {
			listener.ChannelChanged(channel);
		}
	}

}
